package ltd.yangyh.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.ResourceBundle;

@Configuration
@MapperScan("ltd.yangyh.mapper")
@EnableTransactionManagement
public class MybatisConfig {
    @Bean
    DruidDataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        ResourceBundle database = ResourceBundle.getBundle("database");
        druidDataSource.setDriverClassName(database.getString("database.driver"));
        druidDataSource.setUrl(database.getString("database.url"));
        druidDataSource.setUsername(database.getString("database.username"));
        druidDataSource.setPassword(database.getString("database.password"));
        return druidDataSource;
    }

    @Bean
    SqlSessionFactoryBean sqlSessionFactory(DruidDataSource druidDataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(druidDataSource);
        PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLogImpl(StdOutImpl.class);
        sqlSessionFactoryBean.setConfiguration(configuration);
        try {
            sqlSessionFactoryBean.setMapperLocations(patternResolver.getResources("classpath*:mapperxml/*Mapper.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlSessionFactoryBean;
    }

    @Bean
    PlatformTransactionManager transactionManager(DruidDataSource druidDataSource) {
        return new DataSourceTransactionManager(druidDataSource);
    }
}
